/*
 * @Author: yangzonglong
 * @Date: 2021-02-05 15:16:41
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: TLL
 * @LastEditTime: 2021-02-24 14:15:07
 * @Auditor: 
 */
import React, { useCallback, forwardRef, useImperativeHandle, useState } from 'react';
import { Radio, Tabs } from 'antd';
import { RadioChangeEvent } from 'antd/lib/radio/interface';
import styles from './tabs.module.scss';

const RadioGroup = Radio.Group;
const Button = Radio.Button;
const TabPane = Tabs.TabPane;
const handleLabel = (data: CornemarkType, id: string, label: string) => {
  if (typeof data[id] === 'number') {
    return label + `(${data[id]})`;
  }
  return label;
};

export type TabItem = { id: string; label?: string; };

export interface TabsProps {
  tabs: TabItem[];
  curTabId: string;
  onChange(id: string): void;
  mode?: 'tabs' | 'radio';
  tabBarExtraContent?: any;
  className?: any;
  [propName: string]: any;
}

type CornemarkType = {
  id?: string;
  count?: number;
};

export interface TabsRefProps {
  setCornermark(data: CornemarkType): void;
  onTabClick?(data: string): void;
}

export default forwardRef(({
  tabs,
  curTabId,
  onChange,
  onTabClick,
  mode,
  tabBarExtraContent,
  className
}: TabsProps, ref: React.Ref<TabsRefProps>) => {
  const [cornermark, setCornermark] = useState<CornemarkType>({});

  const _onChange = useCallback((e: RadioChangeEvent | string) => {
    onChange(typeof e === 'string' ? e : e.target.value);
  }, [onChange]);

  useImperativeHandle(ref, () => {
    return {
      setCornermark: (data) => {
        setCornermark(data);
      }
    };
  });

  return (
    <div className={styles.box}>
      {mode !== 'tabs' ? (
        <RadioGroup onChange={_onChange} value={curTabId}>
          {tabs.map(item => <Button value={item.id} key={item.id}>{item.label}</Button>)}
        </RadioGroup>
      ) : (
        <Tabs activeKey={curTabId} onChange={_onChange} onTabClick={(v) => onTabClick?.(v)} tabBarExtraContent={tabBarExtraContent} className={className}>
          {tabs.map(item => <TabPane key={item.id} tab={handleLabel(cornermark, item.id, item.label!)} />)}
        </Tabs>
      )}
    </div>
  );
});